/*
 License
 
 Copyright © 2012 Kevin Kimmich
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights to 
 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 the Software, and to permit persons to whom the Software is furnished to do so, 
 subject to the following conditions:
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "crcore.h"

__inline__ void invalidate(stringbuffer* sb)
{
	if (sb->data) {
		free(sb->data);
	}
	sb->data = NULL;
}

void sb_init(stringbuffer* sb, char* cb)
{
	sb->data=cb;
	stream_init(&sb->s,UNBOUNDED);
	if(cb)
	{
		stream_from_memory(&sb->s,cb,strlen(cb));
	}
}

stringbuffer* sb_create(void)
{
	stringbuffer *sb = malloc(sizeof(stringbuffer));
	sb_init(sb, NULL);
	return sb;
}

void sb_destroy(stringbuffer *sb) 
{
	if(sb) 
	{
		sb_delete_buffer(sb);
		free(sb);
	}
}

void sb_replace(stringbuffer* sb, char* buf, int len)
{
	if(sb->data)
		free(sb->data);
	
	stream_cleanup(&sb->s);
	stream_from_memory(&sb->s,buf,len);
	sb->data=buf;
}

stringbuffer* sb_copy( stringbuffer* dst,stringbuffer* src )
{
	if(dst->data)
		free(dst->data);
	if(src->data)
		dst->data=strdup(src->data);
	else
		dst->data=NULL;
	
	stream_duplicate(&src->s,&dst->s);
	return dst;
}

void sb_add_data(stringbuffer *sb, const char *cb) 
{
	invalidate(sb);
	stream_from_memory(&sb->s,(char*)cb,strlen(cb));
}

char *sb_get_buffer(stringbuffer *sb) {
  if(!sb->data)
  {
	  sb->data = stream_to_string_keep(&sb->s,NULL);
  }
  return sb->data;
}

void sb_delete_buffer(stringbuffer *sb) {
  if (sb->data) {
    free(sb->data);
  }
  sb->data = NULL;
  stream_cleanup(&sb->s);
}

unsigned int sb_get_length(stringbuffer *sb) {
  return stream_length(&sb->s);
}

void sb_sprintf(stringbuffer *sb, const char *format, ...) {
  va_list list;
  va_start( list , format );
  
  stream_vprintf(&sb->s,format,list);
  
  va_end(list);
}

void sb_copy_data(stringbuffer *sb, char *cb, int length) {
	stream_from_memory(&sb->s,cb,length);
}

void sb_truncate(stringbuffer *sb) {
  invalidate(sb);
  stream_cleanup(&sb->s);
}

int sb_compare(stringbuffer *a, stringbuffer *b) {
	return stream_strcmp(&a->s,&b->s);
}
